package com.dream.technology.service.impl;


import com.dream.technology.components.riskControl.SymbolAnalysis;
import com.dream.technology.components.riskControl.tianji.RcConstan;
import com.dream.technology.db.dao.RcCustomerTagMapper;
import com.dream.technology.db.dao.RcFlowMapper;
import com.dream.technology.db.entity.*;
import com.dream.technology.db.entity.vo.VoCustomerTag;
import com.dream.technology.service.RcCustomerTagItemService;
import com.dream.technology.service.RcCustomerTagService;
import com.dream.technology.service.RcFlowItemService;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service("rcCustomerTagService")
public class RcCustomerTagServiceImpl implements RcCustomerTagService {

    private static final Logger logger = LoggerFactory.getLogger(RcCustomerTagService.class);

    @Autowired
    RcCustomerTagMapper rcCustomerTagMapper;
    @Autowired
    SymbolAnalysis symbolAnalysis;
//    @Autowired
//    private AdminClient adminClient;
    @Autowired
    private RcFlowItemService rcFlowItemService;
    //     @Autowired
//     private RcCustomerTagItemMapper tagItemMapper;
    @Autowired
    private RcFlowMapper rcFlowMapper;
    @Autowired
    RcCustomerTagItemService rcCustomerTagItemService;


    @Override
    public int countByExample(RcCustomerTagQuery example) {
        return rcCustomerTagMapper.countByExample(example);
    }

    @Override
    public int deleteByExample(RcCustomerTagQuery example) {
        return rcCustomerTagMapper.deleteByExample(example);
    }

    @Override
    public int deleteByPrimaryKey(Long id) {
        return rcCustomerTagMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int insert(RcCustomerTag record) {
        return rcCustomerTagMapper.insert(record);
    }

    /**
     * 插入用户标签 json格式
     *
     * @param customerTag
     * @return
     */
    @Override
    @Transactional
    public String insertTag(VoCustomerTag customerTag) {

        logger.debug("addCustomerTagSetting str ========{}", customerTag);
//        JSONObject json = JSON.parseObject(customerTag);

        //获取管理员id
//        GenericRspDTO<OperationAdmin> userInfo = adminClient.getUserInfoByToken();
//        Integer id = userInfo.getBody().getId();
//        String creator = userInfo.getBody().getUserName();
//        String riskControlClaCode = RandomCode.getRiskControlClaCode();


        List<RcCustomerTagItem> customerTagItems = customerTag.getCustomerTagItems();
        RcCustomerTag cusTag = customerTag.getCustomerTag();
        String desc = checkCustomerTag(customerTag);
        cusTag.setTagRuleDesc(desc);
//        cusTag.setAdminId(Long.valueOf(id));
//        cusTag.setCode(riskControlClaCode);
//        cusTag.setCreator(creator);
        cusTag.setStatus(false);
        //保存CustoemrTag
        insert(cusTag);
        ArrayList<RcCustomerTagItem> tagItems = new ArrayList<>();
        for (int i = 0; i < customerTagItems.size(); i++) {
            // 重新映射 别名与描述
            RcCustomerTagItem item = customerTagItems.get(i);
//            item.setAdminId(Long.valueOf(id));
            item.setTagId(cusTag.getId());
            // 解析民族：["汉","回","藏","苗"] 变成 汉,回,藏,苗
            if (4==item.getFieldDataType()) {
            	item.setFieldValue(item.getFieldValue().replaceAll("\"|\\[|\\]", ""));
            } else {
            	if (item.getFieldValue().contains(",")) {
                	String[] sys = item.getOperationalSymbolCode().split(",");
            		String[] split = item.getFieldValue().split(",");
            		if (sys.length < 2) {
            			item.setFieldValue(split[0]);
            			item.setOperationalSymbolCode(sys[0]);
            		} else {
            			if ("undefined".equals(sys[1])) {
            				item.setFieldValue(split[0]);
            				item.setOperationalSymbolCode(sys[0]);
            			}
            		}
                }
            }
            tagItems.add(item);
        }
        rcCustomerTagItemService.insertList(tagItems);
        return RcConstan.SUCCESS;
    }


    @Override
    @Transactional
    public int insertSelective(RcCustomerTag record) {
        return rcCustomerTagMapper.insertSelective(record);
    }

    @Override
    public List<RcCustomerTag> selectByExample(RcCustomerTagQuery example) {
        return rcCustomerTagMapper.selectByExample(example);
    }

    @Override
    public RcCustomerTag selectByPrimaryKey(Long id) {
        return rcCustomerTagMapper.selectByPrimaryKey(id);
    }

    @Override
    @Transactional
    public int updateByExampleSelective(RcCustomerTag record, RcCustomerTagQuery example) {
        return rcCustomerTagMapper.updateByExampleSelective(record, example);
    }

    @Override
    @Transactional
    public int updateByExample(RcCustomerTag record, RcCustomerTagQuery example) {
        return rcCustomerTagMapper.updateByExample(record, example);
    }

    @Override
    @Transactional
    public int updateByPrimaryKeySelective(RcCustomerTag record) {
        return rcCustomerTagMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    @Transactional
    public int updateByPrimaryKey(RcCustomerTag record) {
        return rcCustomerTagMapper.updateByPrimaryKey(record);
    }


    /**
     * 输入 ale|cd&(jke|iuy)   返回 期数等于7 | 期数等于14 &（性别等同于男）。。。。
     *
     * @param customerTag
     * @return
     */
    @Override
    public String checkCustomerTag(VoCustomerTag customerTag) {
        logger.debug("checkCustomerTagSetting str ========{}", customerTag);

        RcCustomerTag cusTag = customerTag.getCustomerTag();
        List<RcCustomerTagItem> customerTagItems = customerTag.getCustomerTagItems();
        String tagRule = cusTag.getTagRule();


        Map<String, String> itemsMap = new HashMap<>(customerTagItems.size() << 1);
        for (int i = 0; i < customerTagItems.size(); i++) {
            // 重新映射 别名与描述
            RcCustomerTagItem item = customerTagItems.get(i);
            String itemAlias = item.getTagItemAlias();
            String fieldName = item.getFieldName();
            // 解析范围符号
            String symbolCode = item.getOperationalSymbolCode();
            // 解析民族：["汉","回","藏","苗"] 变成 汉,回,藏,苗
            String fieldValue = null;
            if ("nation".equals(item.getFieldCode())) {
            	fieldValue = item.getFieldValue().replaceAll("\"|\\[|\\]", "");
            } else {
            	fieldValue = item.getFieldValue();
            }
            String s = symbolAnalysis.analysisSymbolName(fieldName, symbolCode, fieldValue);
            itemsMap.put(itemAlias, s);
        }


        return symbolAnalysis.getExp(tagRule, itemsMap);

    }

    /**
     * 复制用户标签
     *
     * @param id
     * @param tagName
     * @param tagCode
     * @return
     */
    @Override
    @Transactional
    public String copy(Long id, String tagName, String description, Boolean enabled) {
    	RcCustomerTag rcCustomerTag = rcCustomerTagMapper.selectByPrimaryKey(id);
//    	rcCustomerTag.setCode(RandomCode.getRiskControlClaCode());
        rcCustomerTag.setId(null);
        rcCustomerTag.setTagName(tagName);
        rcCustomerTag.setDescription(description);
        rcCustomerTag.setEnabled(enabled);
        rcCustomerTag.setCreateDate(new Date());
        rcCustomerTagMapper.insertSelective(rcCustomerTag);
        rcCustomerTagItemService.copy(id, rcCustomerTag.getId());
        return RcConstan.SUCCESS;
    }

    /**
     * 修改标签配置
     *
     * @param
     * @return
     */
	@Override
	@Transactional
	public String updateByJsonStr(VoCustomerTag voCustomerTag) {
		logger.debug("checkCustomerTagSetting str ========{}", voCustomerTag);
		// 前端传回来的标签
		RcCustomerTag customerTag = voCustomerTag.getCustomerTag();
		// 原标签
		RcCustomerTag customerTagOld = rcCustomerTagMapper.selectByPrimaryKey(customerTag.getId());
		List<RcCustomerTagItem> customerTagItems = voCustomerTag.getCustomerTagItems();
		String desc = checkCustomerTag(voCustomerTag);
		customerTag.setTagRuleDesc(desc);
		updateByPrimaryKeySelective(customerTag);
		List<RcCustomerTagItem> rcCustomerTagItems = rcCustomerTagItemService.selectByTagId(customerTag.getId());

		ArrayList<Long> itemIds = new ArrayList<>();
		customerTagItems.forEach(item -> {
			if (item.getId() != null) {
				// 解析民族：["汉","回","藏","苗"] 变成 汉,回,藏,苗
	            String fieldValue = null;
	            if (4==item.getFieldDataType()) {
	            	fieldValue = item.getFieldValue().replaceAll("\"|\\[|\\]", "");
	            } else {
	            	fieldValue = item.getFieldValue();
	            }
	            item.setFieldValue(fieldValue);
				// 修改
				rcCustomerTagItemService.updateByPrimaryKeySelective(item);
				itemIds.add(item.getId());
			} else {
				// id 为空 新增
				//获取管理员id
//		        GenericRspDTO<OperationAdmin> userInfo = adminClient.getUserInfoByToken();
//		        Integer id = userInfo.getBody().getId();
				item.setTagId(customerTag.getId());
//				item.setAdminId(Long.valueOf(id));
				item.setStatus(false);
				rcCustomerTagItemService.insertSelective(item);
			}
		});
		// 删除
		List<RcCustomerTagItem> deleteItems = rcCustomerTagItems.stream()
				.filter(item -> !itemIds.contains(item.getId())).collect(Collectors.toList());
		deleteItems.forEach(item -> rcCustomerTagItemService.deleteByPrimaryKey(item.getId()));
		// 修改标签名称，需要同步子流程中引用的此标签的名称
		if (!customerTagOld.getTagName().equals(customerTag.getTagName())) {
			// 查询引用此标签的子流程
			RcFlowItemQuery flowItemQuery = new RcFlowItemQuery();
			RcFlowItemQuery.Criteria criteria = flowItemQuery.createCriteria();
			criteria.andChildItemIdEqualTo(customerTagOld.getId());
			criteria.andChildItemTypeEqualTo(0);
			List<RcFlowItem> flowItemList = rcFlowItemService.selectByExample(flowItemQuery);
			if (CollectionUtils.isNotEmpty(flowItemList)) {
				for (RcFlowItem item : flowItemList) {
					RcFlowItem itemNew = new RcFlowItem();
					itemNew.setId(item.getId());
					itemNew.setChildItemName(customerTag.getTagName());
					rcFlowItemService.updateByPrimaryKeySelective(itemNew);
				}
			}
		}
		return null;
	}

    /**
     * 查询voTag
     * @param tagId
     * @return
     */
    @Override
    public VoCustomerTag selectVoTagByTagId(Long tagId) {
        RcCustomerTag tag = selectByPrimaryKey(tagId);
        List<RcCustomerTagItem> rcCustomerTagItems = rcCustomerTagItemService.selectByTagId(tagId);

        VoCustomerTag voCustomerTag = new VoCustomerTag();
        voCustomerTag.setCustomerTag(tag);
        voCustomerTag.setCustomerTagItems(rcCustomerTagItems);
        return  voCustomerTag;
    }


}
